package yxy.cherry.router;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import yxy.apple.logger.Logger;
import yxy.apple.nio.server.Server;
import yxy.banana.launcher.Reactable;
import yxy.banana.socket.receiver.Observer;
import yxy.cherry.router.Configuration.BindingClass;
import yxy.cherry.router.server.RouterServerCluster;
import yxy.cherry.router.server.RouterServerInitializer;

public class Reactor implements Reactable<Configuration>{
	protected static Logger logger = Logger.create(Reactor.class);
	public final static Reactor instance = new Reactor();

	private RouterServerCluster clustered = new RouterServerCluster();
	private Server server = null;

	private Reactor() {

	}

	public void shutdown() {
		if (this.server != null) {
			logger.info("正在关闭网关服务...");
			this.server.stop();
			logger.info("正在清理等待回应的事务请求...");
			Observer.shared.clear();
		}
	}

	public void start(Configuration configuration) throws Exception {
		logger.info("正在开启服务器...");
		BindingClass bindings[] = configuration.TCPServer.Bindings;
		SocketAddress[] addresses = new SocketAddress[bindings.length];
		for (int i = 0; i < bindings.length; i++) {
			BindingClass binding = bindings[i];
			SocketAddress address = new InetSocketAddress(binding.LocalIP, binding.LocalPort);
			addresses[i] = address;
			logger.info("绑定%s...", address);
		}
		this.server = new Server(new RouterServerInitializer(), configuration.TCPServer.AcceptorThreads,
				configuration.TCPServer.WorkThreads);
		this.server.start(addresses);
	}

	public RouterServerCluster clustered() {
		return this.clustered;
	}

}
